package com.world.business.area.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.world.business.area.domain.Area;
import com.world.business.area.domain.query.AreaPageRequest;
import com.world.business.area.domain.vo.AreaTreeVO;
import com.world.business.area.mapper.AreaMapper;
import com.world.common.enumeration.DelFlagEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 地区 服务实现类
 *
 * @author 邓驴
 * @date 2023/05/13 15:45
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

    @Resource
    private AreaMapper areaMapper;

    @Override
    public List<AreaTreeVO> tree(AreaPageRequest request) {
        LambdaQueryWrapper<Area> queryWrapper = Wrappers.lambdaQuery(Area.class);
        queryWrapper.eq(Area::getDelFlag, DelFlagEnum.NORMAL.getCode());
        queryWrapper.eq(StrUtil.isNotBlank(request.getAreaType()), Area::getAreaType, request.getAreaType());
        List<Area> areas = areaMapper.selectList(queryWrapper);
        return tree(areas, request.getParentId());
    }

    /**
     * 构建地区树
     *
     * @author 邓驴
     * @date 2023/5/13 18:00
     **/
    private List<AreaTreeVO> tree(List<Area> areas, Long parentId) {
        //返回结果
        List<AreaTreeVO> result = new ArrayList<>();

        //查询结果
        List<AreaTreeVO> list = BeanUtil.copyToList(areas, AreaTreeVO.class);
        if (CollectionUtil.isNotEmpty(list)) {
            Map<Long, AreaTreeVO> map = list.stream().collect(Collectors.toMap(AreaTreeVO::getId, Function.identity()));
            //构建树
            Long p = parentId == null ? 0L : parentId;
            list.forEach(i -> {
                if (i.getParentId().equals(p)) {
                    result.add(map.get(i.getId()));
                } else {
                    AreaTreeVO areaTreeVO = map.get(i.getParentId());
                    if (BeanUtil.isNotEmpty(areaTreeVO)) {
                        List<AreaTreeVO> children = areaTreeVO.getChildren();
                        if (CollectionUtil.isEmpty(children)) {
                            children = new ArrayList<>();
                            children.add(i);
                            areaTreeVO.setChildren(children);
                        } else {
                            children.add(i);
                        }
                    }
                }
            });
        }
        return result;
    }


}
